package com.zyy.weather.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.lnold.serverchan.PushResult;
import com.lnold.serverchan.ServerchanProperties;
import com.zyy.weather.dto.ServerDTO;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author LZC
 */
@Service
public class ServerchanService {
    private final String requestUrl;
    private static ObjectMapper mapper = new ObjectMapper();

    ServerchanService(ServerchanProperties properties) {
        this.requestUrl = "https://sctapi.ftqq.com/" + properties.getSckey() + ".send";
    }

    public ServerDTO sendMessage(String title, String content, String channel) {
        RestTemplate client = new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> request = this.generateRequest(title, content,channel);
        String body = client.exchange(this.requestUrl, HttpMethod.POST, request, String.class, new Object[0]).getBody();
        ServerDTO serverDTO = JSONObject.parseObject(body).toJavaObject(ServerDTO.class);
        return serverDTO;
    }

    private HttpEntity<MultiValueMap<String, String>> generateRequest(String text, String desp,String channel) {
        if (StringUtils.isEmpty(text)) {
            throw new IllegalArgumentException("标题不能为空");
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> params = new LinkedMultiValueMap();
            params.add("text", text);
            params.add("desp", desp);
            params.add("channel",channel);
            return new HttpEntity(params, headers);
        }
    }

    private PushResult parseResponse(ResponseEntity<String> response) {
        try {
            return (PushResult)mapper.readValue((String)response.getBody(), PushResult.class);
        } catch (IOException var3) {
            throw new JsonParseException(var3);
        }
    }

    static {
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    }
}
